import { SSHConfig, DeepSeekConfig } from '../types';

export class ValidationError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'ValidationError';
  }
}

export function validateSSHConfig(config: SSHConfig): void {
  if (!config.host || config.host.trim() === '') {
    throw new ValidationError('SSH主机地址不能为空');
  }

  if (!config.username || config.username.trim() === '') {
    throw new ValidationError('SSH用户名不能为空');
  }

  if (!config.password || config.password.trim() === '') {
    throw new ValidationError('SSH密码不能为空');
  }

  if (config.port && (config.port < 1 || config.port > 65535)) {
    throw new ValidationError('SSH端口必须在1-65535范围内');
  }

  if (config.timeout && config.timeout < 1000) {
    throw new ValidationError('SSH超时时间不能少于1000毫秒');
  }
}

export function validateDeepSeekConfig(config: DeepSeekConfig): void {
  if (!config.apiKey || config.apiKey.trim() === '') {
    throw new ValidationError('DeepSeek API密钥不能为空');
  }

  if (config.apiKey.length < 10) {
    throw new ValidationError('DeepSeek API密钥格式不正确');
  }

  if (config.maxTokens && (config.maxTokens < 100 || config.maxTokens > 8192)) {
    throw new ValidationError('maxTokens必须在100-8192范围内');
  }
}

export function validateCommand(command: string, maxLength: number = 1000): void {
  if (!command || command.trim() === '') {
    throw new ValidationError('命令不能为空');
  }

  if (command.length > maxLength) {
    throw new ValidationError(`命令长度不能超过${maxLength}字符`);
  }

  const dangerousPatterns = [
    /rm\s+-rf\s+\/[^/\s]*$/,  // rm -rf / 类似的危险命令
    /:\(\)\{/,                  // fork炸弹模式
    /shutdown/,                 // 关机命令
    /reboot/,                   // 重启命令
    /halt/,                     // 停机命令
    /mkfs/,                     // 格式化文件系统
    /fdisk.*\/dev/,             // 磁盘分区操作
  ];

  for (const pattern of dangerousPatterns) {
    if (pattern.test(command)) {
      throw new ValidationError(`检测到危险命令，拒绝执行: ${command}`);
    }
  }
}

export function validateTaskDescription(description: string): void {
  if (!description || description.trim() === '') {
    throw new ValidationError('任务描述不能为空');
  }

  if (description.length < 5) {
    throw new ValidationError('任务描述过于简短，请提供更详细的描述');
  }

  if (description.length > 500) {
    throw new ValidationError('任务描述过长，请简化描述');
  }
}

export function sanitizeCommand(command: string): string {
  return command.trim().replace(/[;&|`$(){}[\]]/g, '');
}

export function isValidHostname(hostname: string): boolean {
  const hostnameRegex = /^[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*$/;
  return hostnameRegex.test(hostname);
}

export function isValidPort(port: number): boolean {
  return port >= 1 && port <= 65535;
}